package drds.plus.repository.berkeley.spi;

import com.sleepycat.je.TransactionConfig;
import com.sleepycat.je.rep.ReplicaWriteException;
import drds.plus.datanode.api.Connection;
import drds.plus.datanode.api.DatasourceManager;
import drds.plus.executor.ExecuteContext;
import drds.plus.executor.cursor.cursor.Cursor;
import drds.plus.executor.transaction.Transaction;
import drds.plus.executor.transaction.strict_write_with_non_transaction_cross_database_read.ReadWrite;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class TransactionImpl implements Transaction {

    com.sleepycat.je.Transaction transaction;
    TransactionConfig transactionConfig;
    List<Cursor> openedCursors = new LinkedList<Cursor>();

    public TransactionImpl(com.sleepycat.je.Transaction transaction, com.sleepycat.je.TransactionConfig transactionConfig) {
        this.transaction = transaction;
        this.transactionConfig = transactionConfig;

    }

    public long getId() {
        if (transaction == null) {
            throw new IllegalArgumentException("事务为空");
        }
        return transaction.getId();
    }

    public void commit() throws RuntimeException {
        try {
            closeCursor();
            transaction.commit();
        } catch (ReplicaWriteException replicaWrite) {
            try {
                rollback();
            } catch (Exception throwable) {
                throw new RuntimeException(throwable);
            }
        }
    }

    public void rollback() throws RuntimeException {
        if (transaction != null) {
            closeCursor();
            transaction.abort();
            transaction = null;

        }
    }

    private void closeCursor() throws RuntimeException {
        List<RuntimeException> ex = new ArrayList();
        for (Cursor cursor : openedCursors) {
            ex = cursor.close(ex);
        }
        if (!ex.isEmpty()) {
            throw new RuntimeException(ex.get(0));
        }

    }

    public void addCursor(Cursor cursor) {
        openedCursors.add(cursor);
    }

    public List<Cursor> getCursors() {
        return openedCursors;
    }

    public void close() {
        throw new IllegalArgumentException("not supported yet");
    }

    public void setExecuteContext(ExecuteContext executeContext) {


    }

    public drds.plus.executor.transaction.ConnectionHolder getConnectionHolder() {

        return null;
    }

    public void tryClose(String dataNodeId, Connection connection) throws SQLException {

    }

    public boolean isClosed() {

        return false;
    }

    public void kill() throws SQLException {


    }

    public void cancel() throws SQLException {


    }

    public void tryClose() throws SQLException {


    }

    public Connection getConnection(String dataNodeId, DatasourceManager datasourceManager, ReadWrite readWrite) throws SQLException {
        return null;
    }

}
